package main.stack;

import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;

import java.util.Stack;

/**
 * Java 中stack的练习和使用
 * @author: kejl
 * @create: 2020-11-08 10:29
 */
public class StackTest {
    public static void main(String[] args) {
        //1.创建一个字符型的栈
        Stack<Character> stack=new Stack<>();
        System.out.println(stack);
        //2.测试栈是否为空
        System.out.println(stack.empty());
        //3.入栈
        stack.push('a');
        stack.push('b');
        stack.push('c');
        System.out.println(stack);
        //4.查看栈顶元素
        System.out.println(stack.peek());
        System.out.println(stack);
        //5.出栈
        stack.pop();
        System.out.println(stack);
        //6.返回对象在栈中的位置
        System.out.println(stack.search('b'));
        System.out.println(stack.search('a'));
    }
    @Test
    void testStack(){
        Stack<Integer> stack = new Stack<Integer>();
        //添加元素
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.isEmpty();
        int a = stack.peek();

        System.out.println(a);

        System.out.println(stack.empty());

        int b = stack.pop();

        System.out.println(b);

        System.out.println(stack.search(2));

        isValid();
    }

    /**
     * 有效的括号
     * @return
     */
    @Test
     boolean isValid() {
        String s = "({[)";
        if(s == null || "".equals(s)){
            return false;
        }
        Stack<Character> stack = new Stack<Character>();
        char[] chars = s.toCharArray();
        for(char charstr:chars) {
            if (!stack.empty() ) {

                boolean isfindAndPop = false;
                if(stack.peek().charValue()=='(' && charstr ==')'){
                    isfindAndPop = true;
                }

                if(stack.peek().charValue()=='[' && charstr ==']'){
                    isfindAndPop = true;
                }

                if (stack.peek().charValue()=='{' && charstr =='}'){
                    isfindAndPop = true;
                }
                if(isfindAndPop){
                    stack.pop();
                }else{
                    stack.push(charstr);

                }
            } else {
                stack.push(charstr);
            }
        }

            if(stack.empty()){
                return true;
            }else{
                return false;
            }


    }

}
